package com.iman.common.util;

import java.text.DecimalFormat;
import java.util.Calendar;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
 

public class IdCreater {
	
	private static final Log log = LogFactory.getLog(IdCreater.class);
	
	
	private static Long curId = getStartId();
	private static int idCounter = 0;
	
	
	public synchronized static Long getId()
	{
		if(idCounter >= 9999) //重新获取
		{
			curId = getStartId();
			log.info("--------------------------重新获取id:"+ curId);
			idCounter = 0;
		}
		
		//curId += idCounter;
			
		++curId;
		++idCounter;
		return curId;
	}
	//没获取一次，可处理9999条数据
	public static Long getStartId()
	{
		try {
			Thread.sleep(1);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		DecimalFormat numFormat = (DecimalFormat) DecimalFormat.getInstance(); // 格式化数字位数

        Calendar cal = Calendar.getInstance(); // 获取当前时间

        StringBuffer sBuffer = new StringBuffer();
       
        /*if (type != 0) {
            sBuffer.append(type); // 2代表客户
        }
        */
        sBuffer.append("10");     //机器的序号      			//2位
        
        int year = cal.get(Calendar.YEAR);				 // 年 2位
        sBuffer.append(Integer.toString(year).substring(2));

        int day = cal.get(Calendar.DAY_OF_YEAR); //			 日 3位 一年当中的第几天
        numFormat.applyPattern("000");
        sBuffer.append(numFormat.format(day));

        int second = cal.get(Calendar.HOUR_OF_DAY) * 60 * 60
                + cal.get(Calendar.MINUTE) * 60 + cal.get(Calendar.SECOND); // 秒
        
        // 一天当中的第多少秒
        numFormat.applyPattern("00000");                	// 5位
        sBuffer.append(numFormat.format(second));

        int millisecond = cal.get(Calendar.MILLISECOND); // 毫秒 3位
        numFormat.applyPattern("000");
        sBuffer.append(numFormat.format(millisecond));
        
        sBuffer.append("0000");
        
        return Long.parseLong(sBuffer.toString());
	}
	
	
	//---------------------------------------------
	
	public static boolean stringAllEqual(String str)
	{
		for(int i = 0; i < str.length() - 1; i++){
			if(str.charAt(i) != str.charAt(i+1))
				return false; // 分配
		}
		
		return true;
	}
	
	public static  void  main(String...strings ){
		System.out.println(IdCreater.getId());
		
	}
}
